package com.frank.stock4j.dataloader.abstractloader;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.frank.stock4j.tusharepro.BaseBean;
import lombok.SneakyThrows;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class abstractDateRangeLoader<T extends BaseBean, E extends BaseMapper<T>> extends AbstractLoader<T, E> {

    public abstract String getStartDate();
    public abstract Integer getRange();
    String conditionKey = "date";

    public String getStartDateColumn() {
        return "start_date";
    }

    public String getEndDateColumn() {
        return "end_date";
    }

    @SneakyThrows
    @Override
    public List<T> load() {
        Date startDate = DateUtil.parse(getStartDate(), DatePattern.PURE_DATE_PATTERN);
        Map<String, Object> cursor = super.getCursor();
        if (!ObjectUtils.isEmpty(cursor)) {
            startDate = DateUtil.parse(cursor.get(conditionKey).toString(), DatePattern.PURE_DATE_PATTERN);
        }
        Date now = new Date();
        Date endDate = DateUtil.offsetDay(startDate, getRange() - 1);
        do {
            if (endDate.getTime() > now.getTime()) {
                endDate = now;
            }
            this.param(getStartDateColumn(), DateUtil.format(startDate, DatePattern.PURE_DATE_PATTERN));
            this.param(getEndDateColumn(), DateUtil.format(endDate, DatePattern.PURE_DATE_PATTERN));
            this.innerLoad();
            startDate = DateUtil.offsetDay(endDate, 1);
            endDate = DateUtil.offsetDay(startDate, getRange() - 1);
            if (ObjectUtils.isEmpty(cursor)) {
                cursor = new HashMap<>();
            }
            cursor.put(conditionKey, DateUtil.format(startDate, DatePattern.PURE_DATE_PATTERN));
            this.setCursor(cursor);
        } while (endDate.getTime() < now.getTime() && !stoped);

        return null;
    }
}
